<template>
  <div class="login-history-container">
    <h2 class="page-title">登录历史记录</h2>

    <!-- 时间筛选工具栏 -->
    <div class="filter-toolbar">
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="fetchData"
      />
      <el-button
          type="primary"
          :icon="Refresh"
          @click="handleRefresh"
      >刷新</el-button>
    </div>

    <!-- 登录记录表格 -->
    <el-table
        :data="loginHistory"
        style="width: 100%"
        stripe
        v-loading="loading"
        empty-text="暂无登录记录"
    >
      <el-table-column prop="loginTime" label="登录时间" width="180">
        <template #default="{row}">
          {{ formatDateTime(row.loginTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="ipAddress" label="IP地址" width="150">
        <template #default="{row}">
          <el-tooltip :content="getIPLocation(row.ipAddress)" placement="top">
            <span>{{ row.ipAddress }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="device" label="登录设备" width="180">
        <template #default="{row}">
          <div class="device-info">
            <el-icon v-if="row.deviceType === 'mobile'"><Iphone /></el-icon>
            <el-icon v-else><Monitor /></el-icon>
            <span>{{ row.device }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="登录地点">
        <template #default="{row}">
          {{ row.location || '未知地区' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="row.status === '成功' ? 'success' : 'danger'" size="small">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Monitor, Iphone, Refresh } from '@element-plus/icons-vue'
import { userInform } from '@/stores/userInform'
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'

// 定义类型
interface LoginRecord {
  loginTime: string | Date
  ipAddress: string
  device: string
  deviceType: 'mobile' | 'desktop'
  location?: string
  status: '成功' | '失败'
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

interface ApiResponse {
  data: {
    list: LoginRecord[]
    total: number
  }
}

const userStore = userInform()

// 数据状态
const loginHistory = ref<LoginRecord[]>([])
const loading = ref(false)
const dateRange = ref<[string, string] | null>(null)

// 分页配置
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 格式化日期时间
const formatDateTime = (time: string | Date): string => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取IP地理位置（模拟）
const getIPLocation = (ip: string): string => {
  if (ip.startsWith('192.168.')) return '内网IP'
  if (ip.startsWith('10.')) return '内网IP'
  return '中国'
}

// 模拟API请求函数
const getLoginHistory = async (params: {
  page: number
  size: number
  startDate?: string
  endDate?: string
}): Promise<ApiResponse> => {
  // 这里应该是实际的API调用
  // 示例返回模拟数据
  return Promise.resolve({
    data: {
      list: [],
      total: 0
    }
  })
}

// 获取登录历史数据
const fetchData = async (): Promise<void> => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1] || dayjs().format('YYYY-MM-DD')
    }

    const res = await getLoginHistory(params)
    loginHistory.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取登录历史失败:', error)
  } finally {
    loading.value = false
  }
}

// 刷新数据
const handleRefresh = (): void => {
  dateRange.value = null
  pagination.currentPage = 1
  fetchData()
}

// 分页大小变化
const handleSizeChange = (val: number): void => {
  pagination.pageSize = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val: number): void => {
  pagination.currentPage = val
  fetchData()
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.login-history-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}

.filter-toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.device-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
